package com;


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 阻塞队列版的生产者消费者模式
 */
public class BlockingQueueShengchan {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue blockingQueue = new ArrayBlockingQueue(1);
        ThreadResources threadResource = new ThreadResources(blockingQueue);
        new Thread(()->{
            try {
                threadResource.myProd();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"A").start();
        new Thread(()->{
            try {
                threadResource.myConsumer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"B").start();
        Thread.sleep(3000);
        System.out.println("结束  我让你停了");
        threadResource.stop();
    }
}
class ThreadResources{
    private BlockingQueue<String> blockingQueue = null;
    private volatile boolean FLAG =true;
    private AtomicInteger atomicInteger = new AtomicInteger();
    public ThreadResources(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    public void myProd() throws InterruptedException {
        String data = "";
        boolean result;
        while (FLAG){
            data = atomicInteger.incrementAndGet() + "";
            result = blockingQueue.offer(data,2L, TimeUnit.SECONDS);
            if(result){
                System.out.println(Thread.currentThread().getName() + "队列插入成功" + data);
            }else{
                System.out.println(Thread.currentThread().getName() + "队列插入失败" + data);
            }
            Thread.sleep(1000);
        }

        System.out.println("生产结束");
    }

    public void myConsumer() throws InterruptedException {
        String result = "";
        while (FLAG){
            result = blockingQueue.poll(2L,TimeUnit.SECONDS);
            if("".equals(result)||null==result){
//                FLAG = false;
                System.out.println(Thread.currentThread().getName() + "消费失败");
            }else{
                System.out.println(Thread.currentThread().getName() + "消费成功" + result);
            }
        }
    }

    public void stop(){
        this.FLAG = false;
    }
}
